/**
 * time: 2025-09-16
 * author: XJ
 * description: 数字化信息页面（TreeSelect 仅叶子节点 + 完整路径显示）
 */

import React, { useEffect } from 'react';
import { Button, Form, Row, Col, TreeSelect, Space, Cascader, Popconfirm } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import condition from '@/components/staticFile/treeSelect.json';
import { useModel } from '@umijs/max';
import { demand, step1 } from '@/services/apis/companyRegister';

const COMMON_FIELD_STYLE = { width: '100%', height: 40, borderRadius: 4 };
const FORM_LAYOUT = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
  layout: 'horizontal' as const,
  
  size: 'middle' as const,
};

const StepTwoPage: React.FC = () => {
  const [form] = Form.useForm();
  const { stepProps, setStepProps } = useModel('DigitalizationManager.stepProps');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { dataGlobal, setDataGlobal } = useModel('DigitalizationManager.dataGlobal');
  const onFinishFun = () => {
    form.validateFields().then(res => {
      const scenesData = Object.keys(res).filter(item => res[item] != undefined).map(item => ({ label: item, scenes: res[item] }))
      step1({
        "companyId": (initialState?.currentUser as any).data.id,
        scenesData
      }).then(res => {
        setStepProps((prev) => ({ ...stepProps, current: prev.current + 1 }))
      })
    })

  };

  // 递归生成完整路径的 Map，value => 完整路径数组
  const buildFullPathMap = (
    nodes: any[],
    parentPath: string[] = [],
    map: Record<string, string[]> = {},
  ) => {
    nodes.forEach((node) => {
      const currentPath = [...parentPath, node.title];
      map[node.value] = currentPath;
      if (node.children && node.children.length) {
        buildFullPathMap(node.children, currentPath, map);
      }
    });
    return map;
  };
  useEffect(() => {
    // demand({ companyId: (initialState?.currentUser as any).data.id }).then(res => {
    //   const { code, data } = res;
    //   if (code == "0") {
    //     const formData = data.scenesData.reduce((pre: { [x: string]: any; }, cur: { label: string | number; scenes: any; }) => {
    //       pre[cur.label] = cur.scenes
    //       return pre
    //     }, {})
    //     form.setFieldsValue(formData)
    //     debugger
    //   }
    // })
    form.setFieldsValue(dataGlobal.stepTwo)
  }, [dataGlobal.stepTwo])
  const convertNode = (node: any) => ({
    title: node.title,
    value: node.value,
    disabled: node.children && node.children.length > 0, // 非叶子节点禁用
    children: node.children?.map(convertNode),
  });
  return (
    <div style={{ padding: 20, backgroundColor: '#f8f9fa', boxSizing: 'border-box' }}>
      <div
        style={{
          backgroundColor: '#fff',
          padding: 20,
          borderRadius: 8,
          boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
        }}
      >
        <Form disabled={dataGlobal.stepTwoDisabled} {...FORM_LAYOUT} form={form} onFinish={onFinishFun}>
          <div
            style={{
              fontSize: 16,
              fontWeight: 500,
              color: '#1f2937',
              marginBottom: 12,
            }}
          >
            数字化改造需求
          </div>
          {condition.map((item, index) => {
            return (
              <>
                <div
                  style={{
                    fontSize: 16,
                    fontWeight: 500,
                    color: '#1f2937',
                    marginBottom: 12,
                    textIndent: 25
                  }}
                >
                  {item.title.includes(".") ? item.title.split(".")[1] : item.title}面临需求
                </div>
                <Form.List name={`${item.title.includes(".") ? item.title.split(".")[1] : item.title}`}>
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ key, name, ...restField }) => (
                        <div
                          key={key}
                          style={{
                            marginBottom: 24,
                            borderBottom: '1px solid #e8e8e8',
                            paddingBottom: 16,
                          }}
                        >
                          <Row justify="space-between" align="middle">
                            <Col>
                              <div
                                style={{
                                  fontSize: 16,
                                  fontWeight: 500,
                                  color: '#1f2937',
                                  marginBottom: 12,
                                }}
                              >
                                场景 {name + 1}
                              </div>
                            </Col>
                            <Col>
                              <Popconfirm title="是否删除" onConfirm={() => remove(name)}>
                                <Button type="link" danger>
                                  删除
                                </Button>
                              </Popconfirm>

                            </Col>
                          </Row>

                          {/* 场景选择 */}
                          <Form.Item
                            {...restField}
                            label="场景"
                            name={[name, 'scene']}
                            rules={[{ required: true, message: '请选择场景' }]}
                            style={{ marginBottom: 20 }}
                          >
                            <Cascader
                              allowClear
                              placeholder="请选择场景"
                              style={COMMON_FIELD_STYLE}
                              options={[item]}
                              fieldNames={{ label: 'title' }}
                              showSearch
                            />
                          </Form.Item>

                          {/* 场景描述 */}
                          <Form.Item
                            {...restField}
                            label="场景描述"
                            name={[name, 'sceneDesc']}
                            rules={[{ required: true, message: '请输入场景描述' }]}
                            style={{ marginBottom: 20 }}
                          >
                            <TextArea
                              placeholder="请输入场景描述"
                              allowClear
                              showCount
                              maxLength={500}
                              style={{
                                minHeight: 120,
                                maxHeight: 200,
                                resize: 'vertical',
                                ...COMMON_FIELD_STYLE,
                              }}
                            />
                          </Form.Item>

                          {/* 问题及需求分析 */}
                          <Form.Item
                            {...restField}
                            label="问题及需求分析"
                            name={[name, 'problemAnalysis']}
                            rules={[{ required: true, message: '请输入问题及需求分析' }]}
                            style={{ marginBottom: 20 }}
                          >
                            <TextArea
                              placeholder="请输入问题及需求分析"
                              allowClear
                              showCount
                              maxLength={500}
                              style={{
                                minHeight: 120,
                                maxHeight: 200,
                                resize: 'vertical',
                                ...COMMON_FIELD_STYLE,
                              }}
                            />
                          </Form.Item>
                        </div>
                      ))}

                      <Form.Item wrapperCol={{ offset: 5, span: 19 }} style={{ marginTop: 40, textAlign: "center" }}>
                        <Button type="primary" onClick={() => add()} >
                          + 新增场景
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              </>
            );
          })}

          {/* 提交按钮 */}
          <Form.Item
            wrapperCol={{ offset: 5, span: 19 }}
            style={{ marginTop: 80, textAlign: 'center' }}
          >
            <Button
              type="primary"
              // htmlType="submit"
              onClick={onFinishFun}
            >
              下一步
            </Button>
            {/* <Button
              onClick={() => setStepProps((prev) => ({ ...stepProps, current: prev.current - 1 }))}
              type="primary"
               style={{ float: 'right',marginRight:10 }}
            >
              上一步
            </Button> */}
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default StepTwoPage;
